import "./assert/css/index.less";
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import * as XLSX from 'xlsx';
import _basePath from '../basepath';
import { keyClime, clime } from './utils/mission'
import store from "electron-store";
import * as path from 'path';
import { valueMapToKey, download } from './utils/_utils';
import { readFileAsync, appendFile } from './utils/files';
import __basedir from '../basepath';
import sleep from "sleep-promise"
import { remote, ipcRenderer } from 'electron';
const { app } = remote;

console.log(app.getPath("userData"));
Vue.use(ElementUI);
const dataConfigPath = path.join(__basedir, 'datas/data.csv');
let stroge = new store()

const vueApp = new Vue({
    el: '#root',
    data: {
        inputData: [],
        getLinkProcess: 0,
        getPhoneProcess: 0,
        cityDataMap: {},
        threads: 1,
        customCity: '',
        customKeyWord: '',
        hasUsed: [],
    },
    mounted() {
        this.getCity();
        this.getHasUse();
    },
    methods: {
        handleSubmit: function( file:any, fileList: any) {
            const fileReader = new FileReader();
            fileReader.onload = (event: any) => {
                try {
                    const { result } = event.target;
                    const workbook = XLSX.read(result, { type: 'binary', cellText: true});
                    let data: any = [];
                    const workSheets = Object.keys(workbook.Sheets);
                    workSheets.map((item) => {
                        let json_data = XLSX.utils.sheet_to_json(workbook.Sheets[item], {
                            defval: '',
                            header: 'A',
                            raw: false,
                        });
                        data[item] = {
                            json: json_data,
                            merge: workbook.Sheets[item]['!merges'],
                            allInfo: workbook.Sheets[item]
                        };    
                    })
                    this.inputData = data["Sheet1"].json.slice(1);
                    console.log(data["Sheet1"].json)
                    this.$message({
                        message: '读取成功',
                        type: 'success'
                      });
                } catch (e) {
                    console.log(e);
                    this.$message.error('读取失败');
                }
            };
            fileReader.readAsBinaryString(file.raw);
        },
        start: async function() {
            for(let i = 0; i < this.threads; i++) {
                this.run();
                await sleep(5000);
            }
        },
        exportExcel: async function() {
            const fileData: any = await readFileAsync(dataConfigPath);
            const header = ["城市","关键字","地址", "标题", "电话", "链接"];
            let string = header.join(",") + "\n" + fileData.slice(1).toString();
            download(`详情.csv`, string);
        },
        getCity: async function() {
            const cityConfigPath = path.join(__basedir, 'config/city.json');
            const cityData: string | any = await readFileAsync(cityConfigPath);
            let cityDataParse = cityData && JSON.parse(cityData) || []
            const cityDataMap = valueMapToKey(cityDataParse, "label");
            this.cityDataMap = cityDataMap;
            console.log("cityMap", cityDataMap);
        },
        run: async function() {
            console.log(new Date());
            const info: any = this.inputData.pop();
            if(!info) {
                return ;
            }

            let hasUsed: string[] = this.hasUsed;
            if(hasUsed.includes(`${info.A}_${info.B}`)) {
                console.log(`${info.A}_${info.B} 已经爬取过了`);
                this.run();
                return ;
            }
            const cityDataMap: any = this.cityDataMap;
            const cityCode = cityDataMap[info.A].code;
            const keyWord = info.B;
            const key = `${cityCode}_${keyWord}`;

            stroge.set(key + "_pool", []);
            console.log(cityCode, keyWord);
            const keyClimeFlag = stroge.get(`${key}_getLinkProgress`, false);
            let data: any = {};
            if(!keyClimeFlag) {
                data = await keyClime(`http://www.dianping.com/search/keyword/${cityCode}/0_${keyWord}`, key);
                console.log("keyClimeFlag", data);
                stroge.set(`${key}_getLinkProgress`, true);
                console.log(`${key}_getLinkProgress`,stroge.get(`${key}_getLinkProgress`));
            }
            await this.catchClimeError(cityCode, keyWord, info.A);
            stroge.delete(`${key}_getLinkProgress`);
            hasUsed.push(`${info.A}_${info.B}`);
            // localStorage.setItem("hasUsed", JSON.stringify(hasUsed));
            stroge.set("hasUsed", hasUsed);
            if(typeof data.windows != 'undefined') {
                data.windows.close();
            }

            this.run();
        },
        writeInData: async function(data: any[], info: { A: string | number, B: string }) {
            console.log(data);
            const string = data.reduce((prev: any, curr: any) => {
                const { address, name, phone, url, area } = curr;
                return prev += ("\n" + `${info.A},` + `${info.B},` 
                    + `${address.trim().replace(/\,/g, " ")},`  
                    + `${name.trim().replace(/\,/g, " ")},`
                    + `${phone.trim().replace(/\,/g, " ")},`
                    + `${url.trim().replace(/\,/g, " ")},`
                    + `${area[0].trim().replace(/\,/g, " ")},`
                    + `${area[1].trim().replace(/\,/g, " ")}`)
            }, "");
            console.log(string)
            await appendFile(dataConfigPath, string);
        },
        catchClimeError: async function(cityCode: number, keyWord: string, area: string) {
            let flag: any = {};
            let result: any = [];
            const key = `${cityCode}_${keyWord}`;
            flag = await clime(key);
            console.log(flag);
            result = result.concat(stroge.get(key))
            await this.writeInData(result, { A: area, B: keyWord });
            if(typeof flag.windows == 'undefined') {
                return ;
            }
            stroge.set(key, []);
            for(let i = 0; i < flag.windows.length; i++) {
                flag.windows[i].win.close();
            }
        },
        customExport: async function() {
            const cityCode = this.verify();
            if(!cityCode) {
                return ;
            }
            let result: any = [];
            const key = `${cityCode}_${this.customKeyWord}`
            result = result.concat(stroge.get(key, []));
            
            let string = result.reduce((prev: any, curr: any) => {
                const { address, name, phone, url, area } = curr;
                return prev += ("\n"
                    + `${this.customCity},` 
                    + `${this.customKeyWord},` 
                    + `${address.trim().replace(/\,/g, " ")},` 
                    + `${name.trim().replace(/\,/g, " ")},` 
                    + `${phone.trim().replace(/\,/g, " ")},` 
                    + `${url.trim().replace(/\,/g, " ")},`
                    + `${area[0].trim().replace(/\,/g, " ")},`
                    + `${area[1].trim().replace(/\,/g, " ")}`)
            }, "").slice(1);
            const header = ["城市","关键字","地址", "标题", "电话", "链接", "区域1", "区域2"];
            let fileData = header.join(",") + "\n" + string;
            download(`${this.customCity}_${this.customKeyWord}.csv`, fileData);
        },
        removeLink: async function() {
            const flag = this.verify();
            if(!flag) {
                return ;
            }
            const key = `${flag}_${this.customKeyWord}`
            stroge.delete(`${key}_getLinkProgress`);
            this.$message.success("已清空")
        },
        verify: function() {
            if(this.customCity == '' || this.customKeyWord == '') {
                this.$message.error("自定义导出的城市或者关键字不能为空");
                return false;
            }
            const cityDataMap: any = this.cityDataMap;
            const cityCode = cityDataMap[this.customCity] && cityDataMap[this.customCity].code || false;
            if(!cityCode) {
                this.$message.error("没有找到当前城市code");
                return false
            }
            return cityCode
        },
        getHasUse: function() {
            const hasUsed: any = stroge.get("hasUsed", [])
            // let hasUsedParse = hasUsed && JSON.parse(hasUsed) || []
            this.hasUsed = hasUsed
        },
        removeUse: function(tag: string) {
            this.hasUsed.splice((<string[]>this.hasUsed).indexOf(tag), 1);
            const [cityName, keyWord] = tag.split("_");
            const cityDataMap: any = this.cityDataMap;
            const cityCode = cityDataMap[cityName] && cityDataMap[cityName].code
            stroge.set("hasUsed", this.hasUsed)
            stroge.delete(`${cityCode}_${keyWord}_getLinkProgress`);
            stroge.delete(`${cityCode}_${keyWord}_link`);
            stroge.delete(`${cityCode}_${keyWord}`);
            stroge.delete(`${cityCode}_${keyWord}_pool`);
            // localStorage.setItem("hasUsed", JSON.stringify(this.hasUsed));
        },
        getipLeft: function() {
            return stroge.get("ipLeft", 10000);
        }
    },
})

/**
 *
 *
 * @param {string} type // ipLeft, getLinkProcess, getPhoneProcess
 * @param {number} num
 */
function changeProgress(type: string, num: number) {
    console.log(type, num);
    if(type == 'ipLeft') {
        (<any>vueApp)[type] = num;
    } else {
        (<any>vueApp)[type] = num * 100;
    }
   
}

export {
    vueApp,
    changeProgress
}